package spring.chatroom.java_chatroom.common.config.timer;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.EmitUtils;
import org.springframework.web.socket.WebSocketSession;
import spring.chatroom.java_chatroom.common.constant.Constants;
import spring.chatroom.java_chatroom.common.datastructure.SessionQueue;
import spring.chatroom.java_chatroom.common.utils.MailUtil;
import spring.chatroom.java_chatroom.common.utils.WebSocketSessionManagerUtil;
import spring.chatroom.java_chatroom.pojo.WebSocketAndTime;


@Slf4j
public class WebSocketTaskTimer {
    @Autowired
    MailUtil mailUtil;

    @Getter
    @Setter
    private SessionQueue<WebSocketSession, Long> tasks;
    private final Object locker = new Object();

    public WebSocketTaskTimer(SessionQueue tasks) {
        this.tasks = tasks;
        Thread thread = new Thread(this::run);
        thread.start();
    }

    public void add(WebSocketAndTime socketAndTime) {
        synchronized (locker) {
            tasks.put(socketAndTime.getWebSocket(), socketAndTime.getTime());

            if (Constants.TIMER_IS_SLEEPING) {
                //正在等待
                log.info("timer正在睡眠中");
                return;
            }
            locker.notify();
        }
    }

    private void run() {
        log.info("开始检测闲置连接");

        while (true) {
            try {
                synchronized (locker) {
                    //socket列表为空
                    if (tasks.isEmpty()) {
                        log.info("定时器为空 等待");
                        locker.wait();
                    }

                    Long currentTime = System.currentTimeMillis();

                    Long time = tasks.peekV();

                    boolean flag = false;

                    //把队首的闲置的连接给清除了
                    while (time != null && time < currentTime) {
                        //从socket中删除
                        WebSocketSessionManagerUtil.removeAttribute(tasks.peekK());

                        //从定时器中删除
                        WebSocketSession poll = tasks.poll();

                        poll.close();

                        log.info("删除了闲置连接 {}", poll);

                        time = tasks.peekV();

                        flag = true;
                    }
                    if (flag) {
                        //进行了连接的清除
                        continue;
                    }

                    log.info("定时器休眠 {} 毫秒", tasks.peekV() - currentTime);
                    Constants.TIMER_IS_SLEEPING = true;

                    locker.wait(tasks.peekV() - currentTime);

                    Constants.TIMER_IS_SLEEPING = false;
                }

            } catch (Exception e) {
                log.error("定时器发生了错误 {}", e.getMessage(), e);
                log.error("定时器关闭");
                mailUtil.sendSampleMail("tangdeyx2333@163.com", "chat_v2 error", "定时器发生了异常退出了: " + e.getMessage());
                return;
            }
        }
    }
}
